package com.sanbianyinwu.www.User.DocItemOperation;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;

import com.sanbianyinwu.www.Public.DocItem;
import com.sanbianyinwu.www.Public.Function_Library;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;








import com.sanbianyinwu.www.Public.JDBConnection;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
/*
 *  接收订单 servlet
 *  code by xillkey
 * 
 */
public class ReceiveDocItem extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//add
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		Cookie[] cookies=request.getCookies();
		Cookie userIDcCookie = Function_Library.findCookie(cookies, "LoginID");
		//Cookie TrueNamecCookie = Function_Library.findCookie(cookies, "TrueName");
		//String TrueName = TrueNamecCookie.getValue();
		Cookie typeCookie = Function_Library.findCookie(cookies, "type");
		PrintWriter out = response.getWriter();
		int userID ;
		if(userIDcCookie!=null&&!userIDcCookie.getValue().equals("")&&"user".equals(typeCookie.getValue()))
		 {
			userID = Integer.parseInt(userIDcCookie.getValue());
		 
		
		Map<String, String> formData = new HashMap<String, String>();
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(new File(request.getRealPath("/Cache")));
		factory.setSizeThreshold(1024 * 1024 * 20);
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		List<FileItem> items = null;
		try {
			items = upload.parseRequest(request);
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		for (int i = 0; i < items.size(); i++) {
			FileItem item = (FileItem) items.get(i);
			if (item.isFormField()) // 非文件域
			{
				formData.put(item.getFieldName(), item.getString("UTF-8"));

			} else {
				String fileName = item.getName();
				System.out.println(fileName);
				SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 定义格式，不显示毫秒

				Timestamp now = new Timestamp(System.currentTimeMillis());// 获取系统当前时间
				String str = df.format(now);
				
				
				fileName = str + fileName.substring(fileName.lastIndexOf("."),
								fileName.length());
				
				formData.put("docFile", fileName);
				File filedis = new File(request.getRealPath("/Upload"));
				 if(!filedis.exists())
					 if(!filedis.mkdir())
						 System.out.println("创建Upload失败!");
				String path = request.getRealPath("/Upload") + "/" + fileName;
				System.out.println(path);
				FileOutputStream fos = new FileOutputStream(path);
				InputStream is = item.getInputStream();
				byte[] buffer = new byte[1024];
				int len;
				while ((len = is.read(buffer)) > 0) {
					fos.write(buffer, 0, len);
				}
				is.close();
				fos.close();
			}
		}
		
		DocItem item=new DocItem();
		
		item.setprintType(Integer.parseInt(formData.get("printType")));
		item.setpaperType(formData.get("paperType"));
		if(Integer.parseInt(formData.get("printType")) == 2){
			item.setppts(Integer.parseInt(formData.get("ppts")));
		}
		item.setcopies(Integer.parseInt(formData.get("copies")));
		item.setisSingle(Integer.parseInt(formData.get("isSingle")));
		item.setisColor(Integer.parseInt(formData.get("isColor")));
		item.setdocFile(formData.get("docFile"));
		item.setotherRequest(formData.get("otherRequest"));
		item.setTrueName(formData.get("TrueName"));
		item.setstudentNum(formData.get("phone"));
		item.setuserID(userID);
		item.setitemType(Integer.parseInt(formData.get("itemType")));
		item.setitemStatus(1);
		item.setSubTime(System.currentTimeMillis());
		UserDIDBconnect.DocItemAddItem(item);
		if(formData.get("haveTrueName").equals("0"))// 说明在提交订单时才填真实姓名，需要更新user表。
		{
			String sql="update yx_user set TrueName='"+formData.get("TrueName")+"' ,longNum='"+formData.get("phone")+"' where userID="+userID;
			Cookie trueNameCookie = Function_Library.findCookie(cookies, "TrueName");
			Cookie phoneCookie = Function_Library.findCookie(cookies, "phone");
			trueNameCookie.setValue(URLEncoder.encode(formData.get("TrueName"),"UTF-8"));
			phoneCookie.setValue(formData.get("phone"));
			response.addCookie(phoneCookie);
			response.addCookie(trueNameCookie);
			JDBConnection con=new JDBConnection();
			con.executeUpdate(sql);
			con.closeConnection();
		}
		request.setAttribute("item", item);
		request.getRequestDispatcher("WEB-INF/success.jsp").forward(request, response);
		
		 }else if(typeCookie!=null&&"admin".equals(typeCookie.getValue()))
		 {
			 request.setAttribute("error", "工作人员不能自己提交订单");
			 request.getRequestDispatcher("/WEB-INF/err.jsp").forward(request, response);   
		 }
		 else{
			 request.setAttribute("error", "请先登陆");
			 request.getRequestDispatcher("/WEB-INF/err.jsp").forward(request, response);    
			//out.print("登陆超时");
		}
	}
}
